package com.cn.zpark;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.cn.zpark
 * @ClassName: GetAndPostAjaxServletDemo02
 * @Description:
 * @author: RZS
 * @date: 2022/4/28  15:34
 */
@WebServlet("/gpasd.do")
public class GetAndPostAjaxServletDemo02 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应格式及编码方式
        response.setContentType("text/html;charset=utf-8");
        // 接收请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + " : " + password);


        // 返回json格式的数据
        List<User> list = new ArrayList<>();
        list.add(new User(1, "张三", "123456"));
        list.add(new User(2, "李四", "456789"));
        list.add(new User(3, "王五", "000000"));

        // 将list集合转为json字符串
        String json = JSONObject.toJSONString(list);

        // 响应数据
        // 获取输出流
        PrintWriter writer = response.getWriter();
        writer.println(json);


        // 关闭资源
        writer.close();
    }
}
